﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bank
{
    //自定义委托类型
    public delegate void MyDelegate(BigMoneyArgs e);

    public class ATM
    {
        //声明事件
        public event MyDelegate BigMoneyFetched;

        private Bank bank;

        public ATM(Bank bk)
        {
            bank = bk;
        }

        //取款方法
        public bool withdraw(int acc, int quan)
        {
            //取款金额大于10000时，触发事件
            if (quan > 10000)
                BigMoneyFetched(new BigMoneyArgs(acc, quan));
            //取款
            return bank.findCreditAccount(acc).withdrawMoney(quan);
        }

        //存款方法，返回值为坏钞金额
        public int save(int acc, int quan)
        {
            //判断存入钞票张数（每张100元）
            int times = quan / 100;
            //记录坏钞数
            int badCashQuan = 0;
            //循环，每次判断一张钞票是否为坏钞
            for (int i = 0;i < times;i++)
            {
                try
                {
                    Random ra = new Random(int.Parse(DateTime.Now.ToString("HHmmssfff")) + i);
                    int a = ra.Next(3);   //模拟坏钞率约为33%，为0则判定为坏钞，为1、2则判定为好钞
                    if (a == 0)  //为坏钞则抛出异常
                        throw new BadCashException();
                    else   //为好钞则执行存款
                        bank.findCreditAccount(acc).saveMoney(100);
                }
                catch(BadCashException)   //BadCashException异常处理
                {
                    //坏钞金额加100
                    badCashQuan += 100;
                }
                finally { }               
            }
            return badCashQuan;  //返回坏钞金额数
        }

        //获取剩余存款数
        public int getRest(int acc)
        {
            return bank.findCreditAccount(acc).getMoney();
        }

        //获取剩余信用额度
        public int getRestCred(int acc)
        {
            return bank.findCreditAccount(acc).getRestCredit();
        }

        //获取最大信用额度
        public int getTotalCred(int acc)
        {
            return bank.findCreditAccount(acc).getTotalCredit();
        }

        //修改密码
        public void changePwd(int acc, int newPwd)
        {
            bank.findCreditAccount(acc).setPwd(newPwd);
        }

        //获取还款时间
        public DateTime getPayDay(int acc)
        {
            return bank.findCreditAccount(acc).getPayD();
        }
    }
}
